<template>
  <div class="xq-form-wrapper bac-f4f6fa">
    <div class="enterprise-wrapper">
      <div class="left">
        <div class="flex-center-center flex-col">
          <div style="margin-top: 24px">
            <a-upload
              list-type="picture-card"
              :show-upload-list="false"
              class="ant-upload"
              :before-upload="beforeUpload"
              accept=".jpg, .jpeg, .png"
            >
              <div class="xqjr-upload-avatar-inner">
                <img class="xqjr-upload-avatar-img" :src="sitePicShow" alt="" />
                <span class="xqjr-upload-avatar-mask">点击更换</span>
              </div>
            </a-upload>
          </div>
          <selectCompanyGroup class="mt16" :hasLeftIcon="true" :siteIds.sync="siteId" :selectTreeId.sync="selectTreeId" :type.sync="type" />
          <!-- 公司详情 -->
          <div class="company-details mt24 mr24 ml24 mb4">
            <a-row>
              <a-col v-for="item in statisticsData.keyNameList" :key="item.key" :span="12" class="mb12">
                <company-details :title="item.key" :content="item.value" @contentClick="toYongGong" />
              </a-col>
            </a-row>
            <div style="display: flex; justify-content: center">
              <div class="details-button mt30 mb12" @click="toYuanGong">
                <span class="content">查看更多</span>
              </div>
            </div>
          </div>
          <!-- 增值服务 -->
          <div class="company-details mt12 mr24 ml24 mb12" style="padding-top: 12px; padding-bottom: 12px">
            <a-row>
              <a-col :span="12">
                <company-details
                  :imgUrl="require('@/assets/icons/hr_hetong.png')"
                  title="电子合同余量"
                  :content="statisticsData.siteContractLeftCount === -1 ? '∞' : statisticsData.siteContractLeftCount"
                />
              </a-col>
              <a-col :span="12">
                <company-details
                  :imgUrl="require('@/assets/icons/hr_duanxin.png')"
                  title="短信余量"
                  :content="statisticsData.siteMessageLeftCount === -1 ? '∞' : statisticsData.siteMessageLeftCount"
                />
              </a-col>
            </a-row>
          </div>
          <div
            class="company-details mt12 mr24 ml24 mb12"
            style="padding-top: 12px; padding-bottom: 12px; cursor: pointer"
            @click="showDetail"
          >
            <a-row>
              <a-col>
                <div style="display: flex; flex-flow: row">
                  <span class="icon iconfont icon-xinzizonglan"></span>
                  <div style="margin-left: 5px; margin-top: 2px">账面余额</div>
                  <div class="popover-contentSpan" style="margin-left: 10px; margin-top: 4px">明细</div>
                </div>

                <div style="font-weight: bold; font-size: 18px; margin-left: 10px; margin-right: 10px">
                  {{ amount }}
                </div>
              </a-col>
            </a-row>
          </div>
        </div>
      </div>
      <div class="right">
        <right-details :siteId="siteId" />
      </div>
      <a-modal title="余额明细" :visible="bushouTable" width="900px" :destroy-on-close="true" @cancel="handleCancel">
        <template slot="footer">
          <a-button @click="handleCancel"> 取消 </a-button>
          <a-button key="submit" type="primary" @click="handleCancel"> 确定 </a-button>
        </template>
        <div class="headerTitle">
          <a-range-picker
            ref="date"
            class="mr20"
            :placeholder="['开始月份', '结束月份']"
            format="YYYY-MM"
            :value="now"
            :mode="mode2"
            @panelChange="handlePanelChange2"
            @change="onMonthChange"
          >
            <template slot="renderExtraFooter">
              <a-button key="submit" type="primary" style="margin-left: 460px" @click="dateOk"> 确定 </a-button>
            </template>
          </a-range-picker>
          <a-select style="width: 150px" placeholder="请选择" @change="approStatusChange" allowClear>
            <a-select-option value="1"> 客户回款计划 </a-select-option>
            <a-select-option value="2"> 社保回款计划 </a-select-option>
            <a-select-option value="3"> 渠道劳务费结算 </a-select-option>
            <a-select-option value="4"> 费用账单 </a-select-option>
          </a-select>
        </div>
        <div style="margin-bottom: 0px">
          <a-form>
            <a-table
              style="margin-top: 20px"
              :columns="columnKuanxiang"
              :data-source="dataDetail2"
              :scroll="{ x: 700, y: 400 }"
              :pagination="pagination"
              @change="handleTableChange"
              row-key="id"
            >
              <template slot="gmtCreate" slot-scope="text, item">
                <span>{{ moment(item.gmtCreate).format("YYYY-MM-DD HH:mm:ss") }}</span>
              </template>
              <template slot="changeType" slot-scope="text, item">
                <div v-if="item.deleteStatus" style="position: relative">
                  <img style="position: absolute; top: -16px; left: -15px; width: 40px" src="../../assets/img/删除.png" alt="" />
                </div>
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ item.yearly + "年" + item.monthly + "月" + getType(item) }}</span>
                  </template>
                  <span>{{ item.yearly + "年" + item.monthly + "月" + getType(item) }}</span>
                </a-tooltip>
              </template>
              <template slot="changeAmount" slot-scope="text, item">
                <div :style="item.changeAmount > 0 ? 'color:#FA5051' : 'color:#24CDAA'">
                  {{ text }}
                </div>
              </template>
            </a-table>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import CompanyDetails from "./components/companyDetails.vue";
import RightDetails from "./components/rightDetails.vue";
import { selectCompanyAndEmpCountStatisticsReq, updateSitePic, findCompanyGroup, findCompanyBalances, companyBalanceRecords } from "./api";
import { uploadGeneralImg } from "@/api/file/file";
import selectCompanyGroup from "@/components/SelectCompany";
import moment from "moment";
import { mapGetters, mapState } from "vuex";
const columnKuanxiang = [
  {
    title: "款项名称",
    dataIndex: "changeType",
    scopedSlots: { customRender: "changeType" },
    align: "left",
    ellipsis: true,
    width: 150
  },
  {
    title: "用工单位",
    dataIndex: "companyName",
    align: "left",
    ellipsis: true,
    width: 100
  },
  {
    title: "金额",
    dataIndex: "changeAmount",
    scopedSlots: { customRender: "changeAmount" },
    align: "left",
    ellipsis: true,
    width: 80
  },
  {
    title: "余额",
    dataIndex: "afterAmount",
    align: "left",
    ellipsis: true,
    width: 80
  },
  {
    title: "操作时间",
    dataIndex: "gmtCreate",
    scopedSlots: { customRender: "gmtCreate" },
    align: "center",
    ellipsis: true,
    width: 110
  }
];
export default {
  components: { CompanyDetails, RightDetails, selectCompanyGroup },
  data() {
    return {
      ids: null,
      amount: 0,
      dataDetail2: [],
      now: [],
      mode2: ["month", "month"],
      status: null,
      bushouTable: false,
      columnKuanxiang,
      sitePic: require("@/assets/icons/hr_default_logo.png"),
      picUrl: undefined,
      clicked: false,
      selectTreeId: "-1",
      replaceFields: {
        children: "companyList",
        title: "name",
        key: "id",
        value: "id"
      },
      dataList: [],
      siteId: undefined,
      type: undefined,
      pagination: {
        pageSize: 10,
        total: 10,
        size: "default",
        current: 1,
        showQuickJumper: true
      },
      lastNewValue: "",
      statisticsData: {}
    };
  },
  mounted() {},
  watch: {
    checkSiteName(newData) {
      if (this.dataList.length > 0) {
        this.dataList[0].name = newData;
      }
    },
    siteId(newValue) {
      this.lastNewValue = newValue;
      this.selectCompanyAndEmpCountStatistics(newValue);
    }
  },
  computed: {
    ...mapState(["site"]),
    sitePicShow() {
      return this.statisticsData.sitePic || this.sitePic;
    },
    checkSiteName() {
      return this.statisticsData.siteName;
    },
    ...mapGetters({
      SelectedAllIds: "site/SelectedAllIds"
    })
  },
  created() {
    this.siteId = this.SelectedAllIds;
    this.findCompanyGroup();
  },
  methods: {
    getCompanyBalances() {
      let a = [];
      if (this.siteId && this.siteId !== "-1") {
        a = this.siteId.split(",");
      }

      findCompanyBalances(a)
        .then((res) => {
          if (res.data) {
            this.amount = res.data.amount ? res.data.amount : 0;
            this.ids = res.data.ids;
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.companyBalanceRecords();
    },
    getType(item) {
      switch (item.changeType) {
        case 1:
          return "客户回款计划";
        case 2:
          return "社保回款计划";
        case 3:
          return "渠道劳务费结算";
        case 4:
          return "费用账单";
      }
    },
    dateOk() {
      this.$refs.date.$refs.picker.sOpen = false;
    },
    showDetail() {
      this.bushouTable = true;
      this.pagination.current = 1;
      this.companyBalanceRecords();
    },
    // 分页查询明细
    companyBalanceRecords() {
      const param = {
        balanceIds: this.ids,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      if (this.now.length !== 0) {
        param.gmtCreateEnd = moment(this.now[1]).valueOf();
        param.gmtCreateStart = moment(this.now[0]).valueOf();
      }
      if (this.status) {
        param.changeType = parseInt(this.status);
      }

      companyBalanceRecords(param)
        .then((res) => {
          if (res.data) {
            this.dataDetail2 = res.data.entities;
            this.pagination.total = res.data.entityCount;
            this.pagination.pageSize = res.data.pageSize;
            this.pagination.current = res.data.pageNo;
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    handleCancel() {
      this.bushouTable = false;
    },
    handlePanelChange2(value, mode) {
      this.now = value;
      this.mode2 = [mode[0] === "date" ? "month" : mode[0], mode[1] === "date" ? "month" : mode[1]];
      this.pagination.current = 1;
      this.companyBalanceRecords();
    },
    onMonthChange(value) {
      this.now = value;
      this.pagination.current = 1;
      this.companyBalanceRecords();
    },
    approStatusChange(e) {
      this.status = e;
      this.pagination.current = 1;
      this.companyBalanceRecords();
    },
    toYongGong() {
      this.$store.commit("hr/setAdminNavState", "overview");
      this.$router.push({
        path: "/overview/employer"
      });
    },
    toZiGongSi() {
      this.$store.commit("hr/setAdminNavState", "overview");
      this.$router.push({
        path: "/overview/subsidiary"
      });
    },
    toYuanGong() {
      this.$store.commit("hr/setAdminNavState", "overview");
      this.$router.push({
        path: "/overview/staff"
      });
    },
    unique(arr) {
      var res = [];
      var obj = {};
      for (var i = 0; i < arr.length; i++) {
        if (!obj[arr[i]]) {
          obj[arr[i]] = 1;
          res.push(arr[i]);
        }
      }
      return res;
    },
    selectCompanyAndEmpCountStatistics() {
      selectCompanyAndEmpCountStatisticsReq(
        this.site.selectId === -1
          ? {}
          : {
              companyIds: this.siteId,
              type: this.site.selectType || "site"
            }
      )
        .then((res) => {
          if (res.code === 200) {
            this.statisticsData = res.data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.getCompanyBalances();
    },

    updateSitePic() {
      const da = {
        picUrl: this.picUrl
      };
      updateSitePic(da)
        .then((res) => {
          this.$message.success("更换成功");
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    beforeUpload(file) {
      const formData = new FormData();
      formData.append("files", file);
      uploadGeneralImg(formData)
        .then((res) => {
          this.picUrl = res.data[0];
          this.sitePic = this.picUrl;
          this.updateSitePic();
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
      return false;
    },
    findCompanyGroup(value) {
      const data1 = {
        name: value || undefined
      };
      findCompanyGroup(data1)
        .then((res) => {
          this.dataList = this.addTreeSlot(res.data);
          const dataListTemporary = [
            {
              name: this.checkSiteName,
              id: "-1",
              companyList: this.dataList,
              scopedSlots: { title: "custom" }
            }
          ];
          this.dataList = [...dataListTemporary];
          console.log("debug log --> dataList", this.dataList);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // treeData添加字段
    addTreeSlot(data) {
      if (!data) {
        return [];
      }
      data.forEach((el) => {
        el.scopedSlots = { title: "custom" };
        this.addTreeSlot(el.companyList);
      });
      return data;
    }
  }
};
</script>

<style lang="scss">
.enter_columns {
  display: flex;
  flex-flow: columns;
}
.enterprise-wrapper {
  .iconfont {
    color: var(--primary);
  }
  display: flex;
  .ant-upload {
    color: rgba(0, 0, 0, 0);
    .ant-upload-select-picture-card {
      display: table;
      float: left;
      width: 80px;
      height: 80px;
      text-align: center;
      vertical-align: top;
      border-radius: 4px;
      cursor: pointer;
      -webkit-transition: border-color 0.3s ease;
      transition: border-color 0.3s ease;
      .ant-upload {
        padding: 0px;
      }
    }
  }
  .ant-upload.ant-upload-select-picture-card {
    background-color: rgba(250, 250, 250, 0);
    border: 0px dashed #d9d9d9;
    margin-right: 0px;
    margin-bottom: 0px;
  }
  .xqjr-upload-avatar-inner {
    position: relative;
    width: 80px;
    height: 80px;
    border-radius: 4px;
    overflow: hidden;
    cursor: pointer;
    .xqjr-upload-avatar-img {
      width: 100%;
      height: 100%;
    }
    .xqjr-upload-avatar-mask {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      height: 30px;
      background-color: rgba(0, 0, 0, 0.3);
      text-align: center;
      color: #fff;
      line-height: 25px;
      font-size: 12px;
      visibility: hidden;
    }
    &:hover {
      .xqjr-upload-avatar-mask {
        visibility: visible;
      }
    }
  }

  .left {
    background-color: white;
    min-height: calc(100vh - 130px);
    width: 320px;
    margin-bottom: -26px;
    padding-right: 0px;

    .company-title {
      font-size: 18px;
      font-weight: 500;
      color: #3c3d43;
      line-height: 27px;
    }
    .company-details {
      background: #f4f6fa;
      border-radius: 4px;
      width: 272px;
      padding-top: 24px;
      padding-left: 20px;
      padding-right: 20px;
      .details-button {
        cursor: pointer;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #d9d9d9;
        padding: 5px 12px;
        .content {
          font-size: 14px;
          font-weight: 400;
          color: #767885;
          line-height: 21px;
        }
      }
    }
    .recharge-bitton {
      cursor: pointer;
      width: 272px;
      height: 36px;
      background: #f7b500;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 24px;
      .content {
        font-size: 14px;
        font-weight: 500;
        color: #ffffff;
        line-height: 21px;
      }
    }
  }
  .right {
    flex: 1;
    background: #f4f6fa;
    margin-bottom: -26px;
  }
  .mt12 {
    margin-top: 12px;
  }
  .mb12 {
    margin-bottom: 12px;
  }
  .popover-contentSpan {
    font-size: 14px;
    font-weight: 400;
    color: var(--primary);
    line-height: 18px;
  }
}
.headerTitle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  display: flex;
  justify-content: flex-start;
  .block {
    width: 3px;
    height: 20px;
    background-color: var(--primary);
    margin-right: 12px;
  }
}
</style>
